package com.jt.Service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.mapper.CartMapper;
import com.jt.pojo.Cart;
import com.jt.service.DubboCartService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
@Service
public class DubboCartServiceImpl implements DubboCartService {
    @Autowired
    private CartMapper cartMapper;
    @Override
    public List<Cart> findCartList(Long userId) {
        QueryWrapper<Cart>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);

        return cartMapper.selectList(queryWrapper);
    }

    @Override
    public void updateCartNum(Cart cart) {
        Cart cartTemp = new Cart();
        cartTemp.setNum(cart.getNum());
        UpdateWrapper updateWrapper = new UpdateWrapper();
        //根据itemId喝userId可以唯一确定购物行为
        updateWrapper.eq("user_id",cart.getUserId());
        updateWrapper.eq("item_id",cart.getItemId());
        cartMapper.update(cartTemp,updateWrapper);
    }

    @Override
    public void deleteCart(Cart cart) {
        QueryWrapper<Cart>queryWrapper = new QueryWrapper<>(cart);
        cartMapper.delete(queryWrapper);
    }

    @Override
    public void saveCart(Cart cart) {
        QueryWrapper<Cart>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cart.getUserId()).eq("item_id",cart.getItemId());
        Cart cartDB = cartMapper.selectOne(queryWrapper);
        if(cartDB==null){
            cartMapper.insert(cart);
        }else {
            int num = cartDB.getNum()+cart.getNum();
            Cart cartTemp = new Cart();
            cartTemp.setNum(num);
            cartTemp.setId(cartDB.getId());
            cartMapper.updateById(cartTemp);
        }
    }
}
